<template>
  <el-card
    class="login-container"
    shadow="always"
    :body-style="{ padding: '20px' }"
  >
    <div slot="header">
      <span>请登录账号</span>
    </div>
    <el-form
      :model="loginForm"
      :rules="loginRules"
      ref="loginFormRef"
      label-width="80px"
    >
      <el-form-item prop="username">
        <template slot="label">
          <i class="el-icon-user"></i>
        </template>
        <el-input v-model="loginForm.username"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <template slot="label">
          <i class="el-icon-lock"> </i>
        </template>
        <el-input
          type="password"
          v-model="loginForm.password"
          :show-password="true"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="handleLogin"
          :loading="loading"
          >登录</el-button
        >
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { Message } from 'element-ui'
export default {
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码长度不能小于5'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ]
      }
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            await this.$store.dispatch('user/login', this.loginForm)
            this.loading = false
            this.$router.push('/')
            Message({
              type: 'success',
              message: '登录成功，即将跳转到首页...',
              duration: 500
            })
          } catch (error) {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.login-container {
  width: 25rem;
  margin: 100px auto;
}
</style>
